package mm.test;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

public class MockRequestImpl extends MockRequestAdapter implements MockRequest {

	private String path;
	private String requestURI;
	private METHOD method=METHOD.GET;
	private Map<String, String> paras=new HashMap<String, String>();
	private Map<String, Object> attributes=new HashMap<String, Object>();
	
	private MockSession session;

	public MockRequestImpl(MockSession session) {
		this.session=session;
	}

	public void setServletPath(String path) {
		int paramStart=path.indexOf("?")+1;
		if(paramStart>0&&paramStart<path.length()){
			String paramS=path.substring(paramStart);
			String[] params=paramS.split("&");
			for(String param : params){
				if(param.length()<3||param.indexOf("=")<1)
					continue;
				String[] kv=param.split("=");
				String key=kv[0];
				String value=kv[1];
				this.setParameter(key, value);
			}
			path=path.substring(0, path.indexOf("?"));
		}
		this.path=path;
	}

	public MockResponse submit() {
		MockContext mockContext=(MockContext) ((HttpSession)session).getServletContext();
		return mockContext.accept(this);
	}

	public HttpSession getSession() {
		return (HttpSession)session;
	}

	public HttpSession getSession(boolean flag) {
		return (HttpSession)session;
	}

	public String getServletPath() {
		return path;
	}

	public String getMethod() {
		return method.name();
	}

	public void setMethod(METHOD method) {
		this.method = method;
	}

	public void setParameter(String name, String value) {
		paras.put(name, value);
	}

	@Override
	public String getParameter(String name) {
		return paras.get(name);
	}

	@Override
	public Map getParameterMap() {
		Map<String, String[]> map=new HashMap<String, String[]>();
		for(String name:paras.keySet()){
			String value=paras.get(name);
			map.put(name, new String[]{value});
		}
		return map;
	}

	@Override
	public Object getAttribute(String arg0) {
		return attributes.get(arg0);
	}

	@Override
	public void setAttribute(String arg0, Object arg1) {
		attributes.put(arg0, arg1);
	}

	@Override
	public RequestDispatcher getRequestDispatcher(String url) {
		return new MockDispatcher(url);
	}

	@Override
	public Locale getLocale() {
		return Locale.SIMPLIFIED_CHINESE; // FIXME may be changed?
	}

	public void setRequestURI(String requestURI) {
		this.requestURI = requestURI;
	}

	@Override
	public String getRequestURI() {
		return requestURI;
	}

	@Override
	public String getCharacterEncoding() {
		return "UTF-8";
	}

	@Override
	public String getContextPath() {
		return "/abc";
	}

}
